<?php
class NoBusinessBase_Utility_SortAndRangeRequest
{
   protected $mSort = '';
   protected $mStart = '';
   protected $mLimit = '';
   
   public function __construct(Zend_Controller_Request_Abstract $pRequest = null, $defaultSortName = null)
   {
      if(!$pRequest)
         return;

      $params  = NoBusinessBase_Helper_SortAndRangeExtraction::fetch($pRequest, $defaultSortName);
      $this->mSort   = $params['sort'];
      $this->mStart  = $params['start'];
      $this->mLimit  = $params['limit'];
   }

   public function load($range = '0-9999999', array $sort = null)
   {
      $range = 'items=' . $range;
      $rangeParams = NoBusinessBase_Helper_SortAndRangeExtraction::fixRange($range);
      $this->mStart  = $rangeParams['start'];
      $this->mLimit  = $rangeParams['limit'];
      if($sort)
         $this->mSort = $sort;
      else
         $this->mSort = array('Id Desc');
   }

   public function setContentRangeHeader($itemsCount, $totalItemsCount)
   {
      $pFront = Zend_Controller_Front::getInstance();
      if($pFront)
         $pFront->getResponse()->setHeader('Content-Range', $this->getStart() . '-' . $this->getEnd($itemsCount) . '/' . $totalItemsCount);
   }

   public function replaceSortKey($search, $replace)
   {
      foreach($this->mSort as &$sortString)
         $sortString = str_replace($search, $replace, $sortString);
   }

   public function getSort()
   {
      return $this->mSort;
   }

   public function getStart()
   {
      return $this->mStart;
   }

   public function getEnd($count)
   {
      return $this->getStart() + ($count - 1);
   }

   public function getLimit()
   {
      return $this->mLimit;
   }
}
